﻿using FileUpload.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Diagnostics.Runtime.DacInterface;
using SocialExplorer.IO.FastDBF;
using System.Data;
using System.Text;
using System.Xml;

namespace FileUpload.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class GenerateCheckTemplateController : ControllerBase
    {
        /// <summary>
        /// 生成核验模板数据
        /// </summary>
        /// <param name="uploadStuInfoInput"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Post(GenerateCheckTemplate companiesInput)
        {
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            string BaseDirectory = AppContext.BaseDirectory + "\\Temp\\";

            if (!Directory.Exists(BaseDirectory))
            {
                Directory.CreateDirectory(BaseDirectory);
            }
            BaseDirectory += DateTime.Now.ToString("yyyyMMddHHss") + "\\";
            if (!Directory.Exists(BaseDirectory))
            {
                Directory.CreateDirectory(BaseDirectory);
            }

            var odbf = new DbfFile(Encoding.GetEncoding(936));

            string TableName1 = "kaosheng.dbf";
            string filePath1 = BaseDirectory + TableName1;
            odbf.Open(filePath1, FileMode.Create);

            odbf.Header.AddColumn(new DbfColumn("zkzh", DbfColumn.DbfColumnType.Character, 15, 0));
            odbf.Header.AddColumn(new DbfColumn("zjlb", DbfColumn.DbfColumnType.Character, 1, 0));
            odbf.Header.AddColumn(new DbfColumn("zjhm", DbfColumn.DbfColumnType.Character, 36, 0));
            odbf.Header.AddColumn(new DbfColumn("ksxm", DbfColumn.DbfColumnType.Character, 100, 0));
            odbf.Header.AddColumn(new DbfColumn("xb", DbfColumn.DbfColumnType.Character, 2, 0));
            odbf.Header.AddColumn(new DbfColumn("img", DbfColumn.DbfColumnType.Character, 100, 0));
            odbf.Header.AddColumn(new DbfColumn("ss", DbfColumn.DbfColumnType.Character, 3, 0));
            odbf.Header.AddColumn(new DbfColumn("kq", DbfColumn.DbfColumnType.Character, 5, 0));
            odbf.Header.AddColumn(new DbfColumn("kdh", DbfColumn.DbfColumnType.Character, 7, 0));
            odbf.Header.AddColumn(new DbfColumn("kdmc", DbfColumn.DbfColumnType.Character, 100, 0));
            odbf.Header.AddColumn(new DbfColumn("kch", DbfColumn.DbfColumnType.Character, 10, 0));
            odbf.Header.AddColumn(new DbfColumn("kchdz", DbfColumn.DbfColumnType.Character, 100, 0));
            odbf.Header.AddColumn(new DbfColumn("zwh", DbfColumn.DbfColumnType.Character, 3, 0));
            odbf.Header.AddColumn(new DbfColumn("chc", DbfColumn.DbfColumnType.Character, 10, 0));

            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("ZKZH");
            dataTable.Columns.Add("zjlb");
            dataTable.Columns.Add("ZJHM");
            dataTable.Columns.Add("KSXM");
            dataTable.Columns.Add("XB");
            dataTable.Columns.Add("SS");
            dataTable.Columns.Add("KQ");
            dataTable.Columns.Add("KDH");
            dataTable.Columns.Add("KDMC");
            dataTable.Columns.Add("KCH");
            dataTable.Columns.Add("KCHDZ");
            dataTable.Columns.Add("ZWH");
            dataTable.Columns.Add("CHC");

            ProcessingData(companiesInput, dataTable);


            Dictionary<string, string> keyExamTime = new Dictionary<string, string>();

            foreach (DataRow item in dataTable.Rows)
            {
                var orec = new DbfRecord(odbf.Header) { AllowDecimalTruncate = true };
                if (!string.IsNullOrEmpty(item["ZKZH"].ToString()))
                {
                    string[] chcList = item["CHC"].ToString().Trim().Split("、");
                    foreach (var chc in chcList)
                    {
                        orec[0] = item["ZKZH"].ToString().Trim();
                        orec[1] = item["zjlb"].ToString().Trim();
                        orec[2] = item["ZJHM"].ToString().Trim();
                        orec[3] = item["KSXM"].ToString().Trim();
                        orec[4] = item["XB"].ToString().Trim();
                        orec[5] = "";
                        orec[6] = item["SS"].ToString().Trim();
                        orec[7] = item["KQ"].ToString().Trim();
                        orec[8] = item["KDH"].ToString().Trim();
                        orec[9] = item["KDMC"].ToString().Trim();
                        orec[10] = item["KCH"].ToString().Trim();
                        orec[11] = item["KCHDZ"].ToString().Trim();
                        orec[12] = item["ZWH"].ToString().Trim();
                        orec[13] = chc;
                        odbf.Write(orec, true);
                        if (!keyExamTime.ContainsKey(chc))
                        {
                            keyExamTime.Add(chc, chc);
                        }
                    }
                }
            }

            odbf.Close();

            var odbf2 = new DbfFile(Encoding.GetEncoding(936));

            string TableName2 = "changci.dbf";
            string filePath2 = BaseDirectory + TableName2;
            odbf2.Open(filePath2, FileMode.Create);

            odbf2.Header.AddColumn(new DbfColumn("chc", DbfColumn.DbfColumnType.Character, 4, 0));
            odbf2.Header.AddColumn(new DbfColumn("chcmc", DbfColumn.DbfColumnType.Character, 20, 0));
            odbf2.Header.AddColumn(new DbfColumn("kksj", DbfColumn.DbfColumnType.Character, 50, 0));
            odbf2.Header.AddColumn(new DbfColumn("jssj", DbfColumn.DbfColumnType.Character, 50, 0));
            odbf2.Header.AddColumn(new DbfColumn("kssj", DbfColumn.DbfColumnType.Integer, 2, 0));
            odbf2.Header.AddColumn(new DbfColumn("sfqh", DbfColumn.DbfColumnType.Integer, 2, 0));

            var orec2 = new DbfRecord(odbf2.Header) { AllowDecimalTruncate = true };

            int ExamTimeCount = 0;
            List<ExamTimeCode> examTimeCodes = new List<ExamTimeCode>();

            foreach (var item in keyExamTime)
            {
                var examtime = companiesInput.tableTimeData.data.FirstOrDefault(x => x.ExamTimeCode == int.Parse(item.Key.ToString()));
                examTimeCodes.Add(new ExamTimeCode
                {
                    chc = item.Key,
                    chcmc = "第" + item.Key + "场",
                    kksj = examtime != null ? examtime.startTime : DateTime.Now.ToString("yyyyMMdd") + "000000",
                    jssj = examtime != null ? examtime.endTime : DateTime.Now.ToString("yyyyMMdd") + "235900",
                    kssj = "1440",
                    sfqh = "0"
                });
            }

            foreach (var item in examTimeCodes)
            {
                orec2[0] = item.chc;
                orec2[1] = item.chcmc;
                orec2[2] = item.kksj;
                orec2[3] = item.jssj;
                orec2[4] = item.kssj;
                orec2[5] = item.sfqh;
                odbf2.Write(orec2, true);
                ExamTimeCount++;
            }

            odbf2.Close();

            var metadatacopy = AppContext.BaseDirectory + "\\metadata.xml";

            var metadata = BaseDirectory + "metadata.xml";

            System.IO.File.Copy(metadatacopy, metadata, true);

            XmlDocument xmlDocmetadata = new XmlDocument();
            xmlDocmetadata.Normalize();
            xmlDocmetadata.Load(metadata);
            XmlNode nodesmetadata = xmlDocmetadata.LastChild;


            Random random = new Random();

            foreach (XmlNode item in nodesmetadata.ChildNodes)
            {
                switch (item.Name)
                {
                    case "kaoshengshu":
                        item.InnerText = dataTable.Rows.Count.ToString();
                        break;
                    case "changcishu":
                        item.InnerText = ExamTimeCount.ToString();
                        break;
                    case "examid":
                        item.InnerText = random.Next(0, 99999999).ToString().PadLeft(8, '0');
                        break;
                    case "jiancheng":
                        item.InnerText = companiesInput.ExamData.jiancheng;
                        break;
                    case "quancheng":
                        item.InnerText = companiesInput.ExamData.quancheng;
                        break;
                    case "kaikaonianyue":
                        item.InnerText = companiesInput.ExamData.kaikaonianyue;
                        break;
                }
            }
            xmlDocmetadata.Save(metadata);


            return Ok("保存成功!");

        }
        /// <summary>
        /// 处理前端传过来的数据
        /// </summary>
        /// <param name="companiesInput"></param>
        private void ProcessingData(GenerateCheckTemplate companiesInput, DataTable dataTable)
        {
            Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
            foreach (var data in companiesInput.tempData)
            {
                DataRow dataRow = dataTable.NewRow();

                foreach (Correspondence correspondence in companiesInput.SelectData)
                {
                    if (correspondence.type == "0")
                    {
                        dataRow[correspondence.key] = correspondence.value;
                    }
                    else if (correspondence.type == "1")
                    {
                        dataRow[correspondence.key] = data[correspondence.selectValue];
                    }
                    else if (correspondence.type == "2")
                    {
                        string value = data[correspondence.selectValue];
                        if (keyValuePairs.ContainsKey(value))
                        {
                            dataRow[correspondence.key] = keyValuePairs[value];
                        }
                        else
                        {
                            keyValuePairs.Add(value, (keyValuePairs.Count + 1).ToString().PadLeft(2, '0'));
                            dataRow[correspondence.key] = keyValuePairs[value];
                        }
                    }
                }

                dataTable.Rows.Add(dataRow);
            }
        }

    }
}
